package cn.wsxiot.mail;

import com.sun.mail.util.MailSSLSocketFactory;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.security.GeneralSecurityException;
import java.util.Properties;

/**
 * java发送邮件的小demo
 * qq邮箱修改了协议，这里用163邮箱
 * http://www.xiaotanzhu.com/2016/07/30/use-rc4-in-tencent-mail.html
 * http://blog.csdn.net/u012755844/article/details/52651154
 * http://blog.csdn.net/tfy1332/article/details/21604841
 */
public class Main1
{
    public static void main(String[] args) throws GeneralSecurityException,MessagingException {

        Properties props = new Properties();
        // 开启debug调试
        props.setProperty("mail.debug", "true");
        // 发送服务器需要身份验证
        props.setProperty("mail.smtp.auth", "true");
        // 设置邮件服务器主机名
        props.setProperty("mail.host", "smtp.163.com");
        // 发送邮件协议名称
        props.setProperty("mail.transport.protocol", "smtp");
        //开启ssl加密
        MailSSLSocketFactory sf = new MailSSLSocketFactory();
        sf.setTrustAllHosts(true);
        props.put("mail.smtp.ssl.enable", "true");
        props.put("mail.smtp.ssl.socketFactory", sf);

        Session session = Session.getInstance(props);

        Message msg = new MimeMessage(session);
        msg.setSubject("测试用例");
        //设置邮件主体
        StringBuilder builder = new StringBuilder();
        builder.append("测试内容");
        msg.setText(builder.toString());
        msg.setFrom(new InternetAddress("***"));//发送邮箱

        Transport transport = session.getTransport();
        transport.connect("smtp.163.com", "****", "****");//发送邮箱和发送邮箱密码

        transport.sendMessage(msg, new Address[] { new InternetAddress("***") });//接收邮箱
        transport.close();
    }
}